package dao;

import entities.User;
import org.springframework.jdbc.core.JdbcTemplate;

import javax.sql.DataSource;
import java.util.List;

public class UserDAOImpl implements UserDAO {

    private static final String INSERT_USER = "insert into users (username, password, enabled) values (?, ?, ?)";
    private static final String INSERT_USER_AUTHORITY = "insert into authorities (username, authority) values (?, ?)";
    private static final String SELECT_USER = "select users.username,password,authority from users,authorities where users.username = ? and users.username=authorities.username";
    private static final String SELECT_ALL_USERS = "select users.username,password,authority from users,authorities where users.username=authorities.username";
    private static final String DELETE_USER = "delete from users where username = ?";
    private static final String DELETE_USER_AUTHORITY = "delete from authorities where username = ?";
    private static final String UPDATE_USER = "update authorities set authority = ? where username = ?";
    private static final String SELECT_ALL_BY_ROLE = "select users.username,password,authority from users,authorities where users.username=authorities.username and authority = ?";
    private static final String UPDATE_USER_PASS = "update users set password = ? where username = ?";
    private JdbcTemplate jdbcTemplateObject;

    public void setDataSource(DataSource dataSource) {
        this.jdbcTemplateObject = new JdbcTemplate(dataSource);
    }

    public void create(User user) {
        String query = INSERT_USER;
        jdbcTemplateObject.update(query, user.getUsername(), user.getPassword(), true);
        query = INSERT_USER_AUTHORITY;
        jdbcTemplateObject.update(query, user.getUsername(), "ROLE_USER");
    }

    public User getUser(String name) {
        String query = SELECT_USER;
        return jdbcTemplateObject.queryForObject(query,
                new Object[]{name}, new UserMapper());
    }

    public List<User> listUsers() {
        String query = SELECT_ALL_USERS;
        return jdbcTemplateObject.query(query,
                new UserMapper());
    }

    public void delete(String name) {
        String query = DELETE_USER_AUTHORITY;
        jdbcTemplateObject.update(query, name);
        query = DELETE_USER;
        jdbcTemplateObject.update(query, name);
    }

    public void update(String name, String role) {
        String query = UPDATE_USER;
        jdbcTemplateObject.update(query, role, name);
    }

    public List<User> getUsersByRole(String role) {
        String query = SELECT_ALL_BY_ROLE;
        return jdbcTemplateObject.query(query,
                new Object[]{role},
                new UserMapper());
    }

    public void updatePass(String name, String pass) {
        String query = UPDATE_USER_PASS;
        jdbcTemplateObject.update(query, pass, name);
    }
}